package com.suxin.oci.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author Tang
 * @classname SupplyStatisticsDataSourceConfig
 * @description [ 供气统计数据源 ]
 * @date 2021/4/24 18:31
 */
@Configuration
@MapperScan(basePackages = {"com.suxin.oci.mapper.oci"},
        sqlSessionTemplateRef = "defaultSqlSessionTemplate")
public class DefaultDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource defaultDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "defaultSqlSessionFactory")
    public SqlSessionFactory defaultSqlSessionFactory(@Qualifier(value = "defaultDataSource") DataSource defaultDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(defaultDataSource);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "defaultTransactionManager")
    public PlatformTransactionManager defaultTransactionManager(@Qualifier(value = "defaultDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate defaultSqlSessionTemplate(@Qualifier(value = "defaultSqlSessionFactory") SqlSessionFactory defaultSqlSessionFactory) {
        return new SqlSessionTemplate(defaultSqlSessionFactory);
    }

}